package com.kinon.ogt.view.activities;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.ogt.GlideApp;
import com.kinon.ogt.R;
import com.kinon.ogt.api.OgtApi;
import com.kinon.ogt.api.service.ServiceFactory;
import com.kinon.ogt.model.User;
import com.kinon.ogt.utils.ImageUtils;
import com.kinon.ogt.utils.RxUtils;
import com.kinon.ogt.utils.SPrefsUtils;
import com.kinon.ogt.utils.ToastUtils;
import com.kinon.ogt.view.widget.CircleImageView;
import com.kinon.ogt.view.widget.FxToolbar;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONException;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 佛祖保佑 永无BUG
 *
 * @author 339
 * @date 2018/5/18
 */
public class UserInfoActivity extends AppCompatActivity {

    private static final String IMG_HEAD_URI = "file:///sdcard/parkinapp/head.jpg";

    @BindView(R.id.toolbar)
    FxToolbar mToolbar;
    @BindView(R.id.iv_user_info_avatar)
    CircleImageView mIvAvatar;
    @BindView(R.id.tv_user_info_nickname)
    TextView mTvNickname;
    @BindView(R.id.tv_user_info_phone_number)
    TextView mTvPhoneNumber;

    private User mUser;
    private String mToken;

    private Disposable mDisposable;
    private OgtApi mOgtApi;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);

        mToolbar.setTitle("我的信息");
        mToolbar.setOnBackClickListener(v -> onBackPressed());
        setSupportActionBar(mToolbar);

        initData();
    }

    private void initData() {
        mOgtApi = ServiceFactory.getOgtApi();
        mToken = SPrefsUtils.readToken();

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        Intent intent = getIntent();
        if (null != intent) {
            if (intent.getParcelableExtra("USER") != null) {
                mUser = intent.getParcelableExtra("USER");
                initView();
            }
        }

    }

    private void initView() {
        GlideApp.with(this)
                .load(mUser.getPic())
                .into(mIvAvatar);

        mTvNickname.setText(mUser.getName());
        mTvPhoneNumber.setText(mUser.getPhone());
    }

    @OnClick(R.id.rl_user_info_nickname)
    public void onNicknameClicked() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_edit, null);
        EditText etEdit = dialogView.findViewById(R.id.et_edit);
        new AlertDialog.Builder(this)
                .setTitle("修改昵称")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    String name = etEdit.getText().toString();
                    updateUserName(name);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void updateUserName(String name) {
        mDisposable = mOgtApi.updateUserInfo(mToken, name)
                .compose(RxUtils.rxSchedulerHelper())
                .subscribe(baseResponse -> {
                    if (baseResponse.isCode()) {
                        ToastUtils.showShort(this, baseResponse.getMsg());
                        setResult(0, new Intent());
                        mTvNickname.setText(name);
                    }
                });
    }

    @OnClick(R.id.rl_user_info_avatar)
    public void onAvatarClicked() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_photo, null);
        TextView tvPhotograph = dialogView.findViewById(R.id.tv_photograph);
        TextView tvCamera = dialogView.findViewById(R.id.tv_camera);
        TextView tvCancel = dialogView.findViewById(R.id.tv_cancel);

        Dialog avatarDialog = new Dialog(this, R.style.Dialog);
        avatarDialog.setContentView(dialogView);

        Window window = avatarDialog.getWindow();
        if (null != window) {
            window.setGravity(Gravity.BOTTOM);
            WindowManager m = getWindowManager();
            WindowManager.LayoutParams lp = avatarDialog.getWindow().getAttributes();
            lp.x = 0;
            lp.y = 0;
            lp.width = getResources().getDisplayMetrics().widthPixels;
            dialogView.measure(0, 0);
            lp.height = dialogView.getMeasuredHeight();
            window.setAttributes(lp);
        }

        avatarDialog.setCancelable(true);
        avatarDialog.setCanceledOnTouchOutside(false);
        avatarDialog.show();

        tvPhotograph.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, 1);
            avatarDialog.dismiss();
        });

        tvCamera.setOnClickListener(v -> {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //下面这句指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
                    .getExternalStorageDirectory() + "/Ogt/",
                    mUser.getPhone() + "_" + System.currentTimeMillis() + ".png")));
            startActivityForResult(intent, 2);
            avatarDialog.dismiss();
        });

        tvCancel.setOnClickListener(v -> avatarDialog.dismiss());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_CANCELED) {
            switch (requestCode) {
                // 如果是直接从相册获取
                case 1:
                    startPhotoZoom(data.getData());
                    break;
                // 如果是调用相机拍照时
                case 2:
                    File temp = new File(Environment.getExternalStorageDirectory()
                            + "/Ogt/" + mUser.getPhone() + "_" + System.currentTimeMillis() + ".png");
                    startPhotoZoom(Uri.fromFile(temp));
                    break;
                // 取得裁剪后的图片
                case 3:
                    if (data != null) {
                        setPicToView(data);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Intent picData) {
        Bundle extras = picData.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            //图片路径
            String urlPath = ImageUtils.saveFile(this,
                    mUser.getPhone() + "_" + System.currentTimeMillis() + ".png", photo);
            System.out.println("----------路径----------" + urlPath);
            getUploadToken(urlPath);
        }
    }

    private void getUploadToken(String urlPath) {
        mDisposable = mOgtApi.getUploadToken()
                .compose(RxUtils.rxSchedulerHelper())
                .compose(RxUtils.handleResult())
                .subscribe(token -> uploadUserAvatar(token.getToken(), urlPath));
    }

    private void uploadUserAvatar(String token, String urlPath) {
        Configuration config = new Configuration.Builder()
                .chunkSize(256 * 1024)
                .putThreshhold(512 * 1024)
                .connectTimeout(10)
                .responseTimeout(60)
                .build();

        UploadManager uploadManager = new UploadManager(config);
        uploadManager.put(urlPath, null, token,
                (key, info, response) -> {
                    if (info.isOK()) {
                        try {
                            String url = response.getString("key");
                            updateUserAvatar(urlPath, url);
                        }catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                },
                new UploadOptions(null, null, false, new UpProgressHandler() {
                    @Override
                    public void progress(String key, double percent) {
                        Log.w("TAG", "progress: " + percent);
                    }
                }, null));
    }

    private void updateUserAvatar(String urlPath, String key) {
        mDisposable = mOgtApi.updateUserAvatar(mToken, key)
                .compose(RxUtils.rxSchedulerHelper())
                .subscribe(baseResponse -> {
                    if (baseResponse.isCode()) {
                        Toast.makeText(UserInfoActivity.this,
                                "修改头像成功", Toast.LENGTH_SHORT).show();
                        GlideApp.with(UserInfoActivity.this)
                                .load(urlPath)
                                .into(mIvAvatar);
                    }
                });
    }

    @OnClick(R.id.rl_user_info_phone_number)
    public void onPhoneNumberClicked() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mDisposable) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
